<?php

namespace Biz;

use Aliyun\Ecs\Request\V20140526 as Ecs;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use live\Request\V20161101\DescribeLiveStreamOnlineUserNumRequest;
use vod\Request\V20170321\DeleteVideoRequest;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;


class AliyunLive
{
    private $vhost;
    private $appName;
    private $privateKey;
    private $accessKey;
    private $accessSecret;

    public function __construct($config)
    {
        $this->vhost = $config['host'];
        $this->appName = $config['app_name'];
        $this->accessKey = $config['access_key'];
        $this->accessSecret = $config['access_secret'];
        $this->privateKey = $config['private_key'];
    }

    /**
     * 生成鉴权key
     *
     * @param string $streamName 流名称，一般与业务相关
     * @param int $expired 有效时长(秒)
     * @return string
     */
    private function genAuthKey($streamName, $expired)
    {
        $time = time() + $expired;
        $rand = 0;
        $uid = 0;
        $sstring = "/{$this->appName}/{$streamName}-{$time}-{$rand}-{$uid}-{$this->privateKey}";
        $key = "{$time}-{$rand}-{$uid}-" . md5($sstring);
        return $key;
    }

    /**
     * 获取直播推/拉地址
     *
     * @param string $streamName 流名称，一般与业务相关
     * @param int $expired 推流地址有效时长（秒）
     * @return array push为推流地址 pull为拉流地址，包含 rtmp flv m3u8
     */
    public function getLiveUrls($streamName, $auth = true, $expired = 3000)
    {
        $rst = [];
        $rst['push'] = $this->getPublishUrl($streamName, $auth, $expired);
        $rst['pull'] = $this->getPullUrl($streamName, $auth, $expired);
        return $rst;
    }

    private function getPublishUrl($streamName, $auth, $expired)
    {
        $url = "rtmp://video-center.alivecdn.com/{$this->appName}/{$streamName}";
        $params = [];
        $params['vhost'] = $this->vhost;
        if ($auth === true) $params['auth_key'] = $this->genAuthKey($streamName, $expired);
        $url = $url . '?' . http_build_query($params);
        return  $url;
    }

    /**
     * 直播播放地址由不同参数拼接而成，由 播放域名 + AppName + StreamName + “_“ + 转码模板名称
     *
     * @param string $streamName
     * @return array
     */
    private function getPullUrl($streamName, $auth, $expired)
    {   
        $rtmpStreamName = $streamName;
        $flvStreamName = $streamName . '.flv';
        $m3u8StreamName = $streamName . '.m3u8';
        if ($auth === true) {
            $rtmp = "rtmp://{$this->vhost}/{$this->appName}/{$streamName}?auth_key=" . $this->genAuthKey($rtmpStreamName, $expired);
            $flv =  "http://{$this->vhost}/{$this->appName}/{$streamName}.flv?auth_key=" . $this->genAuthKey($flvStreamName, $expired);
            $m3u8 = "http://{$this->vhost}/{$this->appName}/{$streamName}.m3u8?auth_key=" . $this->genAuthKey($m3u8StreamName, $expired);
        } else {
            $rtmp = "rtmp://{$this->vhost}/{$this->appName}/{$streamName}";
            $flv =  "http://{$this->vhost}/{$this->appName}/{$streamName}.flv";
            $m3u8 = "http://{$this->vhost}/{$this->appName}/{$streamName}.m3u8";
        }
        return compact('rtmp', 'flv', 'm3u8');
    }

    /**
     * 获取实时在线人数
     *
     * @return array [[push_url] => [nums]]
     */
    public function getOnlineNums()
    {
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config');
        
        $iClientProfile = \DefaultProfile::getProfile('cn-shanghai', $this->accessKey, $this->accessSecret);
        $client = new \DefaultAcsClient($iClientProfile);
        $request = new DescribeLiveStreamOnlineUserNumRequest();
        $request->setDomainName($this->vhost);
        $request->setAppName($this->appName);
        // $request->setStreamName('15_060275_0624');
        $response = $client->getAcsResponse($request);

        $onlineInfo = [];
        foreach ($response->OnlineUserInfo->LiveStreamOnlineUserNumInfo as $info) {
            $onlineInfo[$info->StreamUrl] = $info->UserNumber;
        }
        return $onlineInfo;
    }

    public function getVodAuthKey($vid)
    {
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config');
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-vod/vod/Request/V20170321/GetVideoPlayAuthRequest');
        $profile = \DefaultProfile::getProfile('cn-shanghai', $this->accessKey, $this->accessSecret);
        $client = new \DefaultAcsClient($profile);
        $request = new \GetVideoPlayAuthRequest();
        $request->setVideoId($vid);
        try {
            $response = $client->getAcsResponse($request);
            return $response->PlayAuth;
        } catch (\Exception $e) {}
    }

    /**
     * 删除视频
     *
     * @param [type] $vid
     * @return void
     */
    public function delVideo($vid)
    {
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config');
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-vod/vod/Request/V20170321/DeleteVideoRequest');
        $profile = \DefaultProfile::getProfile('cn-shanghai', $this->accessKey, $this->accessSecret);
        $client = new \DefaultAcsClient($profile);
        $request = new DeleteVideoRequest();
        $vid = is_array($vid) ? implode(',', $vid) : $vid;
        $request->setVideoIds($vid);
        try {
            $response = $client->getAcsResponse($request);
        } catch (\Exception $e) {}
    }

    public function createUploadVideo()
    {
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config');
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-vod/vod/Request/V20170321/CreateUploadVideoRequest');
        $profile = \DefaultProfile::getProfile('cn-shanghai', $this->accessKey, $this->accessSecret);
        $client = new \DefaultAcsClient($profile);
        $request = new \vod\Request\V20170321\CreateUploadVideoRequest();
        $request->setTitle("视频标题");
        $request->setAcceptFormat('JSON');

        //视频源文件名称(必须包含扩展名)
        $request->setFileName("aaaa.mp4");
        //视频源文件字节数
        $request->setFileSize(0);
        $request->setDescription("视频描述");
        //自定义视频封面URL地址
        $request->setCoverURL("http://cover.sample.com/sample.jpg");
        //上传所在区域IP地址
        // $request->setIP("127.0.0.1");
        // $request->setTags("标签1,标签2");
        //视频分类ID
        // $request->setCateId(0);
        $response = $client->getAcsResponse($request);
        return json_decode(json_encode($response), true);
        // dump($response);

    }

    public function getVideoInfo($vid)
    {
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config');
        vendor('aliyun-openapi-php-sdk/aliyun-php-sdk-vod/vod/Request/V20170321/GetPlayInfoRequest');
        $profile = \DefaultProfile::getProfile('cn-shanghai', $this->accessKey, $this->accessSecret);
        $client = new \DefaultAcsClient($profile);
        $request = new \vod\Request\V20170321\GetPlayInfoRequest();
        $request->setVideoId($vid);
        try {
            $response = $client->getAcsResponse($request);
            return array_map(function($info) {
                return json_decode(json_encode($info), true);
            }, $response->PlayInfoList->PlayInfo);
        } catch (\Exception $e) {

        }

    }

    public function setAppName($appName)
    {
        $this->appName = $appName;
    }

    public function setPrivateKey($privateKey)
    {
        $this->privateKey = $privateKey;
    }

    public function setVhost($vhost)
    {
        $this->vhost = $vhost;
    }

    public function setAccessKey($accessKey)
    {
        $this->accessKey = $accessKey;
    }

    public function setAccessSecret($accessSecret)
    {
        $this->accessSecret = $accessSecret;
    }
}
